<?php
require __DIR__ . '/file_storage.php';

// 基本认证
$admin_user = 'admin';
$admin_pass = 'change_me_now'; // 从config.php同步

if (!isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])
    || $_SERVER['PHP_AUTH_USER'] !== $admin_user
    || $_SERVER['PHP_AUTH_PW'] !== $admin_pass) {
    header('WWW-Authenticate: Basic realm="VisitorLog Admin"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Auth required';
    exit;
}

// 获取所有日志文件
function get_all_log_files() {
    $files = glob(__DIR__ . '/logs_*.json');
    rsort($files); // 按日期降序排列
    return $files;
}

// 获取特定日期的日志或所有日志
function get_logs_filtered($date = null, $limit = null, $offset = 0) {
    $all_logs = [];
    $files = $date ? [__DIR__ . '/logs_' . $date . '.json'] : get_all_log_files();
    
    foreach ($files as $file) {
        if (file_exists($file)) {
            $logs = json_decode(file_get_contents($file), true) ?: [];
            // 添加文件名作为参考
            foreach ($logs as &$log) {
                $log['source_file'] = basename($file);
            }
            $all_logs = array_merge($all_logs, $logs);
        }
    }
    
    // 按时间降序排序
    usort($all_logs, function($a, $b) {
        return strcmp($b['ts'], $a['ts']);
    });
    
    if ($limit) {
        return array_slice($all_logs, $offset, $limit);
    }
    return $all_logs;
}

// 清理旧日志（删除文件）
if (isset($_GET['prune']) && ctype_digit($_GET['prune'])) {
    $days = (int)$_GET['prune'];
    $cutoff_date = date('Y-m-d', strtotime("-{$days} days"));
    
    $files = get_all_log_files();
    $deleted = 0;
    foreach ($files as $file) {
        $file_date = str_replace(['logs_', '.json'], '', basename($file));
        if ($file_date < $cutoff_date) {
            unlink($file);
            $deleted++;
        }
    }
    
    header('Location: admin_file.php?deleted=' . $deleted);
    exit;
}

// 清理当天数据
if (isset($_GET['clear_today'])) {
    $today_file = __DIR__ . '/logs_' . date('Y-m-d') . '.json';
    if (file_exists($today_file)) {
        $cleared = count(json_decode(file_get_contents($today_file), true) ?: []);
        unlink($today_file);
        header('Location: admin_file.php?cleared=' . $cleared);
    } else {
        header('Location: admin_file.php?cleared=0');
    }
    exit;
}

// CSV 导出
if (isset($_GET['csv'])) {
    $date = $_GET['date'] ?? null;
    $logs = get_logs_filtered($date);
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=logs' . ($date ? "_$date" : '') . '.csv');
    $out = fopen('php://output', 'w');
    
    // 写入CSV头部
    fputcsv($out, ['时间', '真实IP', 'IP(匿名)', 'UA哈希', 'Ref哈希', '路径', '方法', '同意', 'UA原文', '纬度', '经度', '精度', '地图链接', '来源文件']);
    
    foreach ($logs as $log) {
            $map_link = '';
            if ($log['gps_lat'] && $log['gps_lng']) {
                $map_link = "https://www.google.com/maps?q={$log['gps_lat']},{$log['gps_lng']}";
            } else {
                $ip = $log['ip_real'] ?? $log['ip_anonymized'];
                $map_link = "https://tmini.net/api/ipinfo?ip=" . urlencode($ip);
            }
        
        fputcsv($out, [
            $log['ts'],
            $log['ip_real'] ?? '',
            $log['ip_anonymized'],
            substr($log['ua_hash'], 0, 12) . '...',
            $log['ref_hash'] ? substr($log['ref_hash'], 0, 12) . '...' : '',
            $log['path'],
            $log['method'],
            $log['consent'] ? '是' : '否',
            $log['ua_raw'] ? '是' : '否',
            $log['gps_lat'] ?? '',
            $log['gps_lng'] ?? '',
            $log['gps_accuracy'] ? $log['gps_accuracy'] . 'm' : '',
            $map_link,
            $log['source_file']
        ]);
    }
    fclose($out);
    exit;
}

// 分页参数
$page = max(1, (int)($_GET['p'] ?? 1));
$per_page = 50;
$date_filter = $_GET['date'] ?? null;

// 获取所有日志
$all_logs = get_logs_filtered($date_filter);
$total = count($all_logs);
$pages = max(1, (int)ceil($total / $per_page));
$offset = ($page - 1) * $per_page;
$logs = array_slice($all_logs, $offset, $per_page);

// 获取可用日期列表
$dates = array_map(function($file) {
    return str_replace(['logs_', '.json'], '', basename($file));
}, get_all_log_files());

?>
<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>文件存储管理后台</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;margin:2rem;line-height:1.6;color:#111827}
        .card{max-width:1200px;margin:auto;border:1px solid #e5e7eb;border-radius:12px;padding:24px;box-shadow:0 1px 8px rgba(0,0,0,.04)}
        .muted{color:#6b7280;font-size:14px}
        .btn{display:inline-block;padding:.6rem 1rem;border-radius:8px;border:0;cursor:pointer;text-decoration:none;color:#111827}
        .primary{background:#2563eb;color:#fff}
        .ghost{background:#f3f4f6;color:#111827}
        .row{margin-top:.8rem}
        table{border-collapse:collapse;width:100%;font-size:14px}
        th,td{border:1px solid #e5e7eb;padding:.5rem;text-align:left}
        th{background:#f9fafb;font-weight:600}
        .small{font-size:12px}
        .nowrap{white-space:nowrap}
        .filter-bar{background:#f9fafb;padding:1rem;border-radius:8px;margin-bottom:1rem}
        .ip-location{display:none;margin-top:4px;padding:4px;font-size:11px;background:#f3f4f6;border-radius:4px}
    </style>
    <script>
        function fetchIpLocation(ip) {
            event.preventDefault();
            const btn = event.target;
            const originalText = btn.textContent;
            
            if (btn.dataset.hasLocation) {
                const lat = btn.dataset.lat;
                const lng = btn.dataset.lng;
                window.open(`https://www.google.com/maps?q=${lat},${lng}`, '_blank');
                return;
            }
            
            btn.textContent = '加载中...';
            
            fetch(`https://tmini.net/api/ipinfo?ip=${ip}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0 && data.data.latitude && data.data.longitude) {
                        const lat = data.data.latitude;
                        const lng = data.data.longitude;
                        const location = data.data.location || '未知位置';
                        
                        btn.dataset.lat = lat;
                        btn.dataset.lng = lng;
                        btn.dataset.hasLocation = 'true';
                        btn.textContent = '地图';
                        
                        window.open(`https://www.google.com/maps?q=${lat},${lng}`, '_blank');
                        
                        const cell = btn.parentElement;
                        let locationDiv = cell.querySelector('.ip-location');
                        if (!locationDiv) {
                            locationDiv = document.createElement('div');
                            locationDiv.className = 'ip-location';
                            cell.appendChild(locationDiv);
                        }
                        locationDiv.textContent = `${location} (${lat}, ${lng})`;
                        locationDiv.style.display = 'block';
                    } else {
                        btn.textContent = originalText;
                        alert('无法获取IP位置信息');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    btn.textContent = originalText;
                    alert('获取IP位置失败');
                });
        }
    </script>
</head>
<body>
<div class="card">
    <h2>📊 访问日志管理后台（文件存储版）</h2>
    
    <div class="filter-bar">
        <div class="row">
            <span class="muted">总记录：<?php echo $total; ?> 条</span>
            <span class="muted">｜ 当前页：<?php echo $page; ?>/<?php echo $pages; ?></span>
            <?php if (isset($_GET['deleted'])): ?>
                <span style="color: #059669">✅ 已删除 <?php echo (int)$_GET['deleted']; ?> 个旧文件</span>
            <?php endif; ?>
            <?php if (isset($_GET['cleared'])): ?>
                <span style="color: #059669">✅ 已清空今天 <?php echo (int)$_GET['cleared']; ?> 条记录</span>
            <?php endif; ?>
        </div>
        
        <div class="row">
            <a class="btn primary" href="?csv=1">📥 导出全部CSV</a>
            <a class="btn ghost" href="?prune=30" onclick="return confirm('确定要删除30天前的日志文件吗？');">🗑️ 清理30天前数据</a>
            <a class="btn danger" href="?clear_today=1" onclick="return confirm('确定要清空今天(<?php echo date('Y-m-d'); ?>)的所有记录吗？此操作不可恢复！');" style="background:#dc2626;color:#fff">🗑️ 清空今天数据</a>
            
            <?php if ($date_filter): ?>
                <a class="btn" href="admin_file.php">📅 显示全部</a>
                <a class="btn primary" href="?csv=<?php echo $date_filter; ?>">📥 导出<?php echo $date_filter; ?>数据</a>
            <?php endif; ?>
        </div>
        
        <?php if (count($dates) > 1): ?>
        <div class="row">
            <label>按日期筛选：</label>
            <select onchange="location.href='?date='+this.value">
                <option value="">全部日期</option>
                <?php foreach ($dates as $date): ?>
                    <option value="<?php echo $date; ?>" <?php if ($date === $date_filter) echo 'selected'; ?>>
                        <?php echo $date; ?> (<?php echo count(get_logs_filtered($date)); ?>条)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
    </div>

    <?php if (empty($logs)): ?>
        <p class="muted">暂无访问记录</p>
    <?php else: ?>
        <div style="overflow-x:auto;">
            <table>
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>真实IP</th>
                        <th>IP(匿名)</th>
                        <th>路径</th>
                        <th>方法</th>
                        <th>同意</th>
                        <th>UA原文</th>
                        <th>纬度</th>
                        <th>经度</th>
                        <th>精度</th>
                        <th>地图</th>
                        <th>来源文件</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($logs as $log): ?>
                    <tr>
                        <td class="nowrap small"><?php echo $log['ts']; ?></td>
                        <td class="small"><?php echo htmlspecialchars($log['ip_real'] ?? ''); ?></td>
                        <td class="small"><?php echo htmlspecialchars($log['ip_anonymized']); ?></td>
                        <td><?php echo htmlspecialchars($log['path']); ?></td>
                        <td><?php echo htmlspecialchars($log['method']); ?></td>
                        <td><?php echo $log['consent'] ? '是' : '否'; ?></td>
                        <td><?php echo $log['ua_raw'] ? '是' : '否'; ?></td>
                        <td><?php echo $log['gps_lat'] ? number_format($log['gps_lat'], 4) : ''; ?></td>
                        <td><?php echo $log['gps_lng'] ? number_format($log['gps_lng'], 4) : ''; ?></td>
                        <td><?php echo $log['gps_accuracy'] ? $log['gps_accuracy'] . 'm' : ''; ?></td>
                        <td class="small">
                            <?php if ($log['gps_lat'] && $log['gps_lng']): ?>
                                <a href="https://www.google.com/maps?q=<?php echo $log['gps_lat']; ?>,<?php echo $log['gps_lng']; ?>" target="_blank" class="btn" style="background:#2563eb;color:#fff;padding:2px 6px;font-size:11px">地图</a>
                                <a href="https://uri.amap.com/marker?position=<?php echo $log['gps_lng']; ?>,<?php echo $log['gps_lat']; ?>" target="_blank" class="btn" style="background:#00c250;color:#fff;padding:2px 6px;font-size:11px;margin-left:2px">高德</a>
                            <?php else: ?>
                                <a href="https://tmini.net/api/ipinfo?ip=<?php echo urlencode($log['ip_real'] ?? $log['ip_anonymized']); ?>" target="_blank" class="btn" style="background:#ff6b35;color:#fff;padding:2px 6px;font-size:11px">API</a>
                                 <a href="#" class="btn" style="background:#8b5cf6;color:#fff;padding:2px 6px;font-size:11px;margin-left:2px" onclick="fetchIpLocation('<?php echo htmlspecialchars($log['ip_real'] ?? $log['ip_anonymized']); ?>')">地图</a>
                            <?php endif; ?>
                        </td>
                        <td class="small"><?php echo $log['source_file']; ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if ($pages > 1): ?>
        <div class="row" style="margin-top:1rem;text-align:center;">
            <?php 
            $start = max(1, $page - 3);
            $end = min($pages, $page + 3);
            
            if ($page > 1): ?>
                <a class="btn" href="?p=<?php echo $page-1; ?><?php if ($date_filter) echo '&date='.$date_filter; ?>">上一页</a>
            <?php endif; ?>
            
            <?php for ($i = $start; $i <= $end; $i++): ?>
                <a class="btn" href="?p=<?php echo $i; ?><?php if ($date_filter) echo '&date='.$date_filter; ?>" 
                   <?php if ($i === $page) echo 'style="background:#2563eb;color:#fff;font-weight:700"'; ?>>
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($page < $pages): ?>
                <a class="btn" href="?p=<?php echo $page+1; ?><?php if ($date_filter) echo '&date='.$date_filter; ?>">下一页</a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    <?php endif; ?>
</div>
</body>
</html>